﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel.Syndication;
using System.Xml;
using System.Net;
using System.IO;
using System.Xml.Linq;
using System.Diagnostics;

namespace Channel9WrapperLibrary
{
  public class Shows
  {
    static public string GetShows()
    {
      StringBuilder sb = new StringBuilder();

      bool bfoundlinks = false;
      int page = 1;

      var showList = new List<Show>();

      do
      {

        var showpage = GetShowsList(page);

        if (showpage == null || showpage.Count == 0)
          bfoundlinks = false;
        else
        {
          bfoundlinks = true;
          showList.AddRange(showpage);
        }

        page += 1;

      } while (bfoundlinks);

      foreach (var s in showList)
      {
        sb.AppendFormat("{0} - {1}{2}", s.Title,s.Url,Environment.NewLine);
      }

      return sb.ToString();
    }
    
    static public List<Show> GetShowsList()
    {
      
      bool bfoundlinks = false;
      int page = 1;
      
      var showList = new List<Show>();

      do
      {

        var showpage = GetShowsList(page);

        if (showpage == null || showpage.Count == 0)
          bfoundlinks = false;
        else
        {
          bfoundlinks = true;
          showList.AddRange(showpage);
        }

        page += 1;

      } while (bfoundlinks);

      return showList;
    }

    static public List<Show> GetShowsList(int page)
    {

      var showList = new List<Show>();

      XmlReader reader = XmlReader.Create("http://channel9.msdn.com/Browse/Shows/RSS?sort=atoz&page=" + page.ToString());
      SyndicationFeed feed = SyndicationFeed.Load(reader);

      foreach (var f in feed.Items)
      {
        string thumbnailuri = "";
        var tb = f.ElementExtensions.Where(t => t.OuterName == "thumbnail");

        if (tb.Count() > 0)
        {
          XElement ele = tb.First().GetObject<XElement>();
          thumbnailuri = ele.Attribute("url").Value;
        }

        if (thumbnailuri.StartsWith("/"))
        {
          thumbnailuri = "http://channel9.msdn.com" + thumbnailuri;
        }

        showList.Add(new Show { Title = f.Title.Text, Url = f.Id, ThumbnailUrl = thumbnailuri });

      }
  
      return showList;
    }

    static public List<Episode> GetShowEpisodes(string showurl, string userid, string password, int page)
    {
      var episodeList = new List<Episode>();

      if (!showurl.EndsWith("/"))
        showurl += "/";

      HttpWebRequest request = (HttpWebRequest)WebRequest.Create(showurl +"/atom?page="+page);

      // Set some reasonable limits on resources used by this request
      request.MaximumAutomaticRedirections = 4;
      request.MaximumResponseHeadersLength = 4;

      if (userid.Length>0 && password.Length >0)
        request.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(userid + ":" + password)));

      HttpWebResponse response;
      
      try
      {
        response = (HttpWebResponse)request.GetResponse();
      }
      catch (Exception)
      {
        
        throw;
      }
 
      // Get the stream associated with the response.
      Stream receiveStream = response.GetResponseStream();

      // Pipes the stream to a higher level stream reader with the required encoding format. 
      StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);
      XmlReader reader = XmlReader.Create(readStream);
      SyndicationFeed feed = SyndicationFeed.Load(reader);


      foreach (var f in feed.Items)
      {
        var wmv = f.Links.Where(link => link.Title == "Mp4");

        string thumbnailuri = "";
        string wmvurl = "";

        if (wmv.Count() > 0)
          wmvurl = wmv.First().Uri.ToString();

        if (f.PublishDate.ToLocalTime().Year > 1)
          episodeList.Add(new Episode { 
                    Title = f.Title.Text, 
                    WmvUrl = wmvurl, 
                    ThumbnailUrl = thumbnailuri,
                    Published = f.PublishDate.ToLocalTime(),
                    LastUpdated = f.LastUpdatedTime.ToLocalTime()
                    });
        else
          episodeList.Add(new Episode
          {
            Title = f.Title.Text,
            WmvUrl = wmvurl,
            ThumbnailUrl = thumbnailuri,
            LastUpdated = f.LastUpdatedTime.ToLocalTime()
          });

      }


      response.Close();
      readStream.Close();

      return episodeList;

    }
  }
}
